package com.cj.display_sys.fragment

import android.annotation.SuppressLint
import android.graphics.Rect
import android.text.Html
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_UP
import android.view.View
import android.widget.SeekBar
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.CompositePageTransformer
import androidx.viewpager2.widget.MarginPageTransformer
import androidx.viewpager2.widget.ViewPager2
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cj.display_sys.BaseFragment
import com.cj.display_sys.MainActivity
import com.cj.display_sys.MainViewModel
import com.cj.display_sys.R
import com.cj.display_sys.adapter.ImageAdapter
import com.cj.display_sys.http.ParkEntity
import com.cj.display_sys.http.Picture
import com.cj.display_sys.transformer.AlphaPageTransformer
import com.cj.display_sys.transformer.ScaleInTransformer
import com.cj.display_sys.utils.*
import com.yc.video.tool.PlayerUtils
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_introfuct.*
import kotlinx.android.synthetic.main.fragment_introfuct.img_recycler_View
import kotlinx.android.synthetic.main.fragment_introfuct.tv_park_ind
import kotlinx.android.synthetic.main.fragment_introfuct.tv_park_name
import kotlinx.android.synthetic.main.layout_img.view.*
import java.util.concurrent.TimeUnit

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 *
 * Created by yi on 2021/6/15.
 */
class IntroductionFragment : BaseFragment<MainViewModel>() {

    private lateinit var imgAdapter: BaseQuickAdapter<Picture, BaseViewHolder>
    private var musicPlayer: MusicPlayer? = null
    private val imageAdapter by lazy { ImageAdapter() }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_introfuct
    }

    override fun show() {


    }


    override fun findView() {
        imgAdapter = object : BaseQuickAdapter<Picture, BaseViewHolder>(R.layout.layout_img) {

            override fun convert(holder: BaseViewHolder, item: Picture) {
                holder.itemView.apply {
                    iv_park_img.showImg(item.pictureURL)
                }
            }

        }
        img_recycler_View.apply {
            layoutManager = LinearLayoutManager(activity).apply { orientation = RecyclerView.HORIZONTAL }
            setHasFixedSize(true)
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                    super.getItemOffsets(outRect, view, parent, state)
                    outRect.right = PlayerUtils.dp2px(activity, 60f)
                }
            })
            adapter = imgAdapter

        }
        setViewPager()

    }

    override fun init() {
        getLatestInfo()
    }

    fun getLatestInfo() {
        viewModel.getParkInfo().observe(this, {
            setInfo(it)
        })
        tenGet()

    }

    @SuppressLint("ClickableViewAccessibility")
    override fun setListener() {
        ll_back.setOnClickListener {
            currentSeconds = 0
            disposable?.dispose()
            mediaStop()
            (activity as MainActivity).indexMain()
            (activity as MainActivity).tenGet()
        }
        iv_check.setOnTouchListener { v, event ->
            when (event.action) {
                ACTION_DOWN -> {
                    currentSeconds = 0
                    disposable?.dispose()
                }
                ACTION_UP -> {
                    tenGet()
                }
            }

            false
        }
        iv_check.setOnCheckedChangeListener { buttonView, isChecked ->

            if (isChecked) {
                //播放
                if ((activity as MainActivity).musicPlayer?.isPlaying == true) {
                    (activity as MainActivity).musicPlayer?.pause()
                }
                musicPlayer?.start()
            } else {
                //暂停
                mediaPause()
            }
        }
        ll_i.setOnClickListener {
            currentSeconds = 0
            disposable?.dispose()
            mediaPause()
            (activity as MainActivity).showVideo()
        }

        seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {

            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                seekBar?.progress?.let {
                    iv_check.isChecked = true
                    musicPlayer?.seekTo(it)
                }
            }
        })
        imgAdapter.setOnItemClickListener { adapter, view, position ->
            currentSeconds = 0
            disposable?.dispose()
            tenGet()
            layout_park_banner.isVisible = true
            park_viewPager.post {
                park_viewPager.setCurrentItem(position, false)
            }

        }
        imageAdapter.setOnItemClickListener { adapter, view, position ->
            currentSeconds = 0
            disposable?.dispose()
            tenGet()
        }
        iv_park_close.setOnClickListener {
            layout_park_banner.isVisible = false
            currentSeconds = 0
            disposable?.dispose()
            tenGet()
        }

        park_viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentSeconds = 0
                disposable?.dispose()
                tenGet()
            }
        })

    }

    override fun providerVMClass(): Class<MainViewModel>? {
        return MainViewModel::class.java
    }

    @SuppressLint("SetTextI18n")
    private fun setInfo(parkEntity: ParkEntity) {
        tv_park_name.text = parkEntity.title
        //tv_park_ind.text = parkEntity.content
        tv_park_ind.text = Html.fromHtml(parkEntity.content)
        tv_park_date1.text = "周末开放时间：${parkEntity.weekendOpenTime}"
        tv_park_date2.text = "工作日开放时间：${parkEntity.workOpenTime}"
        tv_park_date3.text = "地址：${parkEntity.address}"
        tv_park_phone.text = "电话：${parkEntity.phone}"
        iv_park_introduce.showImg(parkEntity.videoPicture.pictureURL)
        if (!parkEntity.pictures.isNullOrEmpty()) {
            imgAdapter.setNewInstance(parkEntity.pictures as MutableList<Picture>)
            imageAdapter.setNewInstance(parkEntity.pictures)
        }
        if (parkEntity.mp3Url.isNotEmpty()) {
            initPlayer(parkEntity.mp3Url)
        }
        if (parkEntity.videos.isNullOrEmpty()) {
            ll_i.isVisible = false
        } else {
            ll_i.isVisible = true
            (activity as MainActivity).setVideoUrl(parkEntity.videos[0].pictureURL)
        }
    }

    private fun initPlayer(url: String) {
        musicPlayer = MusicPlayer(url)
        musicPlayer?.setOnSeekListener(object : MusicPlayer.OnSeekListener {
            override fun OnSeek(per_100: Int) {
                seek_bar.progress = per_100
                tv_now.text = per_100.toString()
            }

            override fun onComplete() {
                seek_bar.progress = 0
                tv_now.text = "0"
                iv_check.isChecked = false
            }

            override fun loadComplete() {
                //可以播放音乐了
                iv_check.isChecked = true
                musicPlayer?.start()
            }

        })

    }

    fun mediaPause() {
        musicPlayer?.apply {
            if (isPlaying) {
                iv_check?.isChecked = false
                pause()
            }
        }
    }

    fun mediaStop() {
        musicPlayer?.apply {
            iv_check?.isChecked = false
            tv_now?.text = "0"
            seek_bar?.progress = 0
            onDestroyed()
        }
        musicPlayer = null
    }

    private fun setViewPager() {
        park_viewPager.apply {
            //offscreenPageLimit=1
            val recyclerView = getChildAt(0) as RecyclerView
            recyclerView.apply {
                val padding = resources.getDimensionPixelOffset(R.dimen.dp_10) +
                        resources.getDimensionPixelOffset(R.dimen.dp_10)
                // setting padding on inner RecyclerView puts overscroll effect in the right place
                setPadding(padding, 0, padding, 0)
                clipToPadding = false
            }
        }
        park_viewPager.adapter = imageAdapter
        val compositePageTransformer = CompositePageTransformer()
        compositePageTransformer.addTransformer(AlphaPageTransformer(ScaleInTransformer()))
        compositePageTransformer.addTransformer(MarginPageTransformer(resources.getDimension(R.dimen.dp_40).toInt()))
        park_viewPager.setPageTransformer(compositePageTransformer)
    }


    var disposable: Disposable? = null
    var currentSeconds = 0

    //1、有紧急公告 不播放视频 播放音频 
    //2、普通公告  无操作十分钟之后播放视频
    fun tenGet() {
        currentSeconds = 0
        interval(1, 1, TimeUnit.SECONDS, object : LongObserver() {
            override fun onNext(t: Long) {
                currentSeconds += 1
//                tv_current_seconds1?.post {
//                    tv_current_seconds1?.text = currentSeconds.toString()
//                }
                //LogUtil.e("currentSeconds:$currentSeconds")
                if (currentSeconds == 700) {
                    activity?.runOnUiThread {
                        disposable?.dispose()
                        if ((activity as MainActivity).isNewsFast) {
                            (activity as MainActivity).musicPlayer?.start()
                        } else {
                            (activity as MainActivity).showVideo()
                        }
                    }
                }
            }

            override fun onSubscribe(d: Disposable) {
                disposable = d
            }
        })
    }
}